package com.crb.smartcarddemo.http;

import android.util.Log;


import com.crb.smartcarddemo.utils.LogUtils;
import com.crb.smartcarddemo.utils.MmkvUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HostnameVerifier;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiBase implements HttpLoggingInterceptor.Logger {
    private final String TAG = "ApiBase";
    private final int TIMEOUT = 30;
    //请求日志拦截器
    public HttpLoggingInterceptor mHttpLogInterceptor;

    protected ApiService getService(String ip) {
        mHttpLogInterceptor = new HttpLoggingInterceptor(this);
        //打印http的body体
        mHttpLogInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        LogUtils.e("ApiBase", "baseUrl:" + ip);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new HttpInterceptor())
                .addInterceptor(mHttpLogInterceptor)
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .hostnameVerifier(DO_NOT_VERIFY)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ip)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(ApiService.class);
    }

    private HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;

    @Override
    public void log(String message) {
        if (message.length() > 4000) {
            Log.e(TAG, "sb.length = " + message.length());
            int chunkCount = message.length() / 4000;     // integer division
            for (int i = 0; i <= chunkCount; i++) {
                int max = 4000 * (i + 1);
                if (max >= message.length()) {
                    Log.e(TAG, "chunk " + i + " of " + chunkCount + ":" + message.substring(4000 * i));
                } else {
                    Log.e(TAG, "chunk " + i + " of " + chunkCount + ":" + message.substring(4000 * i, max));
                }
            }
        } else {
            Log.e(TAG, message);
        }
    }

    private class HttpInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();
            HttpUrl url = oldRequest.url();
            String host = url.host();
//            LogUtil.i("111请求地址", host);
            String s = oldRequest.url().encodedPath();
//            LogUtil.i("111请求地址111", s);
            //获取请求体字符串
            Buffer sink = new Buffer();
            oldRequest.body().writeTo(sink);
            String string = sink.readString(Charset.defaultCharset());
            //将请求体字符串签名之后加到请求头
            Request request = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    .headers(oldRequest.headers())
                    .tag(oldRequest.tag())
                    .cacheControl(oldRequest.cacheControl())
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("token", MmkvUtil.decodeString("token"))
//                    .header("sign", SM2Util.signBySM2(string))
//                    .header("publicKey", oldRequest.url().encodedPath().endsWith("login") ? SM2Util.getPublicKeyAndSavePrivatekey() : "")
                    .build();
            return chain.proceed(request);
        }
    }
}
